﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Openlab.Tools.CodeGender.Funtions
{
    public class GetEntitySetFunc : Function
    {
        string entityClass;
        string getIdsFuncName;
        string getEntitiesFuncName;
        string entityCacheName;
        Column idColumn;

        public GetEntitySetFunc(string entityClass, string getIdsFuncName, string getEntitiesFuncName, string entityCacheName, Column idColumn)
            : base(
                string.Format("Get{0}Set", entityClass)
                , string.Format("static PagedResult<{0}>", entityClass)
                , null)
        {
            this.entityClass = entityClass;
            this.getIdsFuncName = getIdsFuncName;
            this.getEntitiesFuncName = getEntitiesFuncName;
            this.entityCacheName = entityCacheName;
            this.idColumn = idColumn;
            Parameters = new List<FunctionParameter>();
            Parameters.Add(new FunctionParameter("pageIndex", "int"));
            Parameters.Add(new FunctionParameter("pageSize", "int"));
            Parameters.Add(new FunctionParameter("idsCacheable", "bool"));
            Parameters.Add(new FunctionParameter("entitiesCacheable", "bool"));
        }

        public override string Body
        {
            get {
                string template = @"
string key = string.Format(""[EntityClass]SetIds"");
List<[IdType]> ids = null;
if (idsCacheable)
    ids = CacheHelper.Get(key) as List<[IdType]>;

if (ids == null)
{
    ids = DataAccess.[GetIdsFunc]();
    CacheHelper.Insert(key, ids, CacheHelper.SecondFactorCalculate(60));
}

return [EntityCache].GetEntitySet(ids, pageIndex,
    pageSize, entitiesCacheable
    , new GetEntitiesFromDatabaseDelegate<[IdType], [EntityClass]>(DataAccess.[GetEntitiesFunc]));
";
                template = template.Replace("[EntityClass]", entityClass);
                template = template.Replace("[EntityCache]", entityCacheName);
                template = template.Replace("[GetIdsFunc]", getIdsFuncName);
                template = template.Replace("[GetEntitiesFunc]", getEntitiesFuncName);
                template = template.Replace("[IdType]", idColumn.CSTypeName);
                return template;
            }
        }
    }
}
